<template>
  <view class="login-container">
    <view class="logo">
      <text class="logo-text">荷叶健康</text>
    </view>
    
    <view class="login-form">
      <view class="input-group">
        <input type="text" v-model="phone" placeholder="请输入手机号" maxlength="11" />
      </view>
      
      <view class="input-group verification">
        <input type="text" v-model="code" placeholder="请输入验证码" maxlength="6" />
        <button class="code-btn" :disabled="codeBtnDisabled" @tap="sendCode">
          {{ codeBtnText }}
        </button>
      </view>
      
      <button class="login-btn" @tap="handleLogin">登录</button>
      <button class="wx-login-btn" @tap="handleWxLogin">
        <text class="wx-icon">🔑</text>
        <text>微信一键登录</text>
      </button>
      
      <view class="divider">
        <text>或</text>
      </view>
      <view class="register-link">
        <text @tap="goToRegister">还没有账号？立即注册</text>
      </view>
    </view>
  </view>
</template>

<script>
import { userApi } from '@/api/user'

export default {
  data() {
    return {
      phone: '',
      code: '',
      codeBtnDisabled: false,
      codeBtnText: '获取验证码',
      timer: null,
      countdown: 60,
      loading: false,
      wxLoginData: null
    }
  },
  methods: {
    async handleWxLogin() {
      if (this.loading) return
      this.loading = true
      
      try {
        // 1. 获取用户信息（必须在点击事件中直接调用）
        const [profileError, profileRes] = await uni.getUserProfile({
          desc: '用于完善会员资料',
          lang: 'zh_CN'
        });
        console.log('获取用户信息---------------:', profileRes);

        if (profileError || !profileRes) {
          console.error('获取用户信息失败:', profileError);
          throw new Error('获取用户信息失败');
        }

        // 2. 获取登录code
        const [loginError, loginRes] = await uni.login({
          provider: 'weixin'
        });

        if (loginError || !loginRes || !loginRes.code) {
          console.error('获取code失败:', loginError);
          throw new Error('获取登录凭证失败');
        }

        // 3. 调用后端接口进行登录，传递用户信息
        const res = await userApi.wxLogin({
          code: loginRes.code,
          avatarUrl: profileRes.userInfo.avatarUrl,
          nickName: profileRes.userInfo.nickName,
          
        })
        
        if (res.code === 200) {
          this.handleLoginSuccess(res)
        } else {
          throw new Error(res.errorMessage || '登录失败')
        }
      } catch (error) {
        console.error('微信登录失败:', error)
        uni.showToast({
          title: error.errMsg || error.message || '登录失败',
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.loading = false
      }
    },
    
    async sendCode() {
      if (this.codeBtnDisabled) return
      
      if (!this.phone || this.phone.length !== 11) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }
      
      try {
        const res = await userApi.sendCode(this.phone)
        if (res.code === 200) {
          this.startCountdown()
          uni.showToast({
            title: '验证码已发送',
            icon: 'success'
          })
        } else {
          throw new Error(res.errorMessage || '发送失败')
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '发送失败',
          icon: 'none'
        })
      }
    },
    
    startCountdown() {
      this.codeBtnDisabled = true
      this.countdown = 60
      this.codeBtnText = `${this.countdown}s后重新获取`
      
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--
          this.codeBtnText = `${this.countdown}s后重新获取`
        } else {
          this.stopCountdown()
        }
      }, 1000)
    },

    stopCountdown() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
      this.codeBtnDisabled = false
      this.codeBtnText = '获取验证码'
    },
    
    async handleLogin() {
      if (!this.phone || !this.code) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        })
        return
      }

      if (this.phone.length !== 11) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }

      if (this.code.length !== 4) {
        uni.showToast({
          title: '请输入4位验证码',
          icon: 'none'
        })
        return
      }
      
      try {
        const res = await userApi.login({
          phone: this.phone,
          code: this.code
        })
        
        if (res.code === 200) {
          this.handleLoginSuccess(res)
        } else {
          throw new Error(res.errorMessage || '登录失败')
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '登录失败',
          icon: 'none'
        })
      }
    },

    // 假设用户登录成功后，在登录函数中获取位置并存储

    onLoginSuccess() {
        // 获取用户位置信息
        uni.getLocation({
            type: 'wgs84', // 使用wgs84坐标系
            success: function (res) {
                // 获取位置信息成功后，存储到本地
                const location = {
                    latitude: res.latitude,  // 纬度
                    longitude: res.longitude,  // 经度
                    speed: res.speed,  // 速度
                    accuracy: res.accuracy  // 精度
                };
                
                // 存储到本地
                uni.setStorageSync('currentLocation', location);
                console.log('位置已存储:', location);
            },
            fail: function (err) {
                console.error('获取位置失败:', err);
            }
        });
    },

    handleLoginSuccess(res) {
      // 保存用户信息
      uni.setStorageSync('userInfo', res.data)
      // 将用户信息同时作为token存储
      uni.setStorageSync('token', res.data)
      // 调用获取位置信息并存储
      this.onLoginSuccess();  // 使用this来调用方法
      
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      })
      
      // 返回上一页或跳转到首页
      setTimeout(() => {
        const pages = getCurrentPages();
        if (pages.length > 1) {
          uni.navigateBack();
        } else {
          uni.switchTab({
            url: '/pages/index/index'
          });
        }
      }, 1500)
    },
    
    goToRegister() {
      uni.navigateTo({
        url: '/pages/register/register'
      })
    },

    async handleGetPhoneNumber(e) {
      if (this.loading) return
      this.loading = true

      try {
        if (e.detail.errMsg !== 'getPhoneNumber:ok') {
          throw new Error('用户拒绝授权手机号')
        }

        // 1. 如果还没有微信登录数据，先进行微信登录
        if (!this.wxLoginData) {
          // 获取登录code
          const [loginError, loginRes] = await uni.login({
            provider: 'weixin'
          })

          if (loginError || !loginRes || !loginRes.code) {
            throw new Error('获取登录凭证失败')
          }

          // 获取用户信息
          const [profileError, profileRes] = await uni.getUserProfile({
            desc: '用于完善会员资料',
            lang: 'zh_CN'
          })

          if (profileError) {
            throw new Error('获取用户信息失败')
          }

          this.wxLoginData = {
            code: loginRes.code,
            userInfo: profileRes.userInfo
          }
        }

        // 2. 调用后端接口，使用手机号code进行登录
        const res = await userApi.wxPhoneLogin({
          code: this.wxLoginData.code,     // 登录code
          phoneCode: e.detail.code,        // 手机号code
          userInfo: this.wxLoginData.userInfo
        })

        if (res.code === 200) {
          // 处理登录成功
          this.handleLoginSuccess(res)
        } else {
          throw new Error(res.errorMessage || '登录失败')
        }
      } catch (error) {
        console.error('微信手机号登录失败:', error)
        uni.showToast({
          title: error.message || '登录失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    }
  },

  beforeDestroy() {
    // 组件销毁前清除定时器
    this.stopCountdown()
  }
}
</script>

<style lang="scss">
.login-container {
  padding: 60rpx 40rpx;
  
  .logo {
    text-align: center;
    margin-bottom: 60rpx;
    
    .logo-text {
      font-size: 48rpx;
      font-weight: bold;
      color: #007AFF;
    }
  }
  
  .login-form {
    .input-group {
      background: #f5f5f5;
      border-radius: 8rpx;
      padding: 20rpx 30rpx;
      margin-bottom: 30rpx;
      
      input {
        height: 80rpx;
        font-size: 28rpx;
      }
      
      &.verification {
        display: flex;
        align-items: center;
        
        input {
          flex: 1;
          margin-right: 20rpx;
        }
        
        .code-btn {
          width: 200rpx;
          height: 80rpx;
          line-height: 80rpx;
          font-size: 26rpx;
          color: #007AFF;
          background: none;
          padding: 0;
          
          &[disabled] {
            color: #999;
          }
        }
      }
    }
    
    .login-btn {
      background: #007AFF;
      color: #fff;
      height: 88rpx;
      line-height: 88rpx;
      border-radius: 44rpx;
      margin-bottom: 30rpx;
    }
    
    .wx-login-btn {
      background: #07C160;
      color: #fff;
      height: 88rpx;
      line-height: 88rpx;
      border-radius: 44rpx;
      margin-bottom: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .wx-icon {
        margin-right: 10rpx;
        font-size: 36rpx;
      }
    }
    
    .divider {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 30rpx;
      
      text {
        color: #999;
        font-size: 24rpx;
        padding: 0 20rpx;
        background: #fff;
      }
      
      &::before,
      &::after {
        content: '';
        flex: 1;
        height: 1rpx;
        background: #eee;
      }
    }
    
    .register-link {
      text-align: center;
      
      text {
        color: #007AFF;
        font-size: 28rpx;
      }
    }
  }
}
</style> 